package com.desmart.renjiao.main;

import com.desmart.renjiao.bean.LoginBean;
import com.desmart.renjiao.bean.LtpaTokenBean;
import com.desmart.renjiao.xmlparase.ResultXmlUtils;
import com.google.gson.Gson;
import com.lemon.library.constants.PreferencesConstants;
import com.lemon.library.net.rx.RxObservableListener;
import com.lemon.library.utils.PreferencesUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class MainP extends Main.MainP{

    @Override
    void tokenPort() {

        long time = PreferencesUtils.getLong(PreferencesConstants.login_Token_save_time);
        if (System.currentTimeMillis() - time < 3 * 60 * 60  * 1000){
            return;
        }

        String cn = null;

        String loginInfoStr = PreferencesUtils.getString(PreferencesConstants.login_info);
        if (loginInfoStr != null){
            LoginBean loginBean = new Gson().fromJson(loginInfoStr, LoginBean.class);
            cn = loginBean.getCn();
            return;
        }

        String xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.destram.cn.com/\">" + "<soapenv:Header/>" +
                "<soapenv:Body><ser:GetToken><!--Optional:--><arg0>" +
                cn +
                "</arg0>" +
                "</ser:GetToken>" +
                "</soapenv:Body>" +
                "</soapenv:Envelope>";

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), xml);
        getRxManager().addObserver(mModel.tokenPort(body), new RxObservableListener<ResponseBody>(mView) {
            @Override
            public void onNext(ResponseBody responseBody) {
                super.onNext(responseBody);
                String ss = null;
                try {
                    ss = responseBody.string();
                    InputStream inputStream = new ByteArrayInputStream(ss.getBytes("UTF-8"));
                    String result = ResultXmlUtils.readXML(inputStream);
                    LtpaTokenBean loginBean = new Gson().fromJson(result, LtpaTokenBean.class);
                    if ("200".equals(loginBean)){
                        String ltpaToken = loginBean.getLtpaToken();
                        PreferencesUtils.putString(PreferencesConstants.login_Token, ltpaToken);
                        PreferencesUtils.putLong(PreferencesConstants.login_Token_save_time,System.currentTimeMillis());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

}
